import axios, {AxiosError, type AxiosRequestConfig, type AxiosResponse} from 'axios';
import useMessage from "@/plugin/useMessage";
import {getToken} from "@/plugin/auth";
// 创建一个 Axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 你的 API 基础 URL
  timeout: 5000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig|any) => {
    // 在请求头中添加 token
      config.headers['Authorization'] = `Bearer ${getToken()}`;
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse|any) => {
      return response.data || <HttpResponse>{};
  },
  (error: AxiosError|any) => {
      useMessage(500, error.response?.data?.message||error.message)
      return Promise.reject({
          code:error.response?.data?.code,
          message:error.response?.data?.message
      });
  }
);

/**
 *
 */
const request = {
  get<T = any>(url: string, params:any,config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, {...config,params}).then(response => response as T);
  },
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config).then(response => response as T);
  },
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config).then(response => response as T);
  },
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config).then(response => response as T);
  },
};

export default request;
